import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,
  Progress, DatePicker, Select,
} from 'antd';
import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';

import find from 'lodash/find';
import debounce from 'lodash/debounce';
import { ellipsis, afterCloseModal, DescriptionItem ,getFileType} from '@/utils/utils';
import { routerRedux } from 'dva/router';
import BuildModalTitle from '@/components/BuildModalTitle';
import MailDetail from './MailDetail';
import ReactDataGrid from 'react-data-grid';
import AddOrEditMeter from './AddOrEdit';
import ForwardForm from './ForwardForm';
import mail from './../../images/mail.png'
import mailOpen from './../../images/mail-open.png'
const FormItem = Form.Item;
const { confirm } = Modal;
const { Option } = Select;

const RadioButton = Radio.Button;

const RadioGroup = Radio.Group;

@connect(({ webMail, loading,global }) => ({
  webMail,
  global,
  loading: loading.models.webMail,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, { name: 'device_add_and_edit' }),
      showdelBtn: find(this.permissions, { name: 'device_delete' }),
      showPasswordBtn: find(this.permissions, { name: 'user_default_password_edit' }),
      user_password_reset: find(this.permissions, { name: 'user_password_reset' }),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      webMail: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        webMail: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'webMail/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'webMail/changeLoaded',
          });
          dispatch({
            type: 'webMail/changeTableY',
          });
        },
      });

    }
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'webMail/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'webMail/changeTableY',
    });
  };
  findChildFunc = (cb)=> {
    this.file=cb
  }

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    const table = document.querySelector('.react-grid-Canvas');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'webMail/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      webMail: { searchParams },
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        {/*<FormItem label="内容">
          {getFieldDecorator('content', {
            initialValue: searchParams.content,
          })(<Input style={{ width: '150px' }} placeholder="请输入"/>)}
        </FormItem>*/}
        <FormItem label="状态">
          {getFieldDecorator('is_read', {
            initialValue: searchParams.is_read,
          })(<Select style={{width:'100px'}}>
            <Option value={'0'}>全部</Option>
            <Option value={'-1'}>未读</Option>
            <Option value={'1'}>已读</Option>
          </Select>)}
        </FormItem>
        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;

                this.handleSearch({
                  page: 1,
                  per_page: searchParams.per_page,
                  ...fieldsValue,
                });

              });
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
        </FormItem>

      </Form>
    );
  }

  handleForward = () => {
    const formValues = this.ForwardForm.props.form.getFieldsValue();
    const checkedList = this.ForwardForm.state.checkedList;
    console.log('checkedList', checkedList);
    const that = this;
    this.props.dispatch({
      type: 'webMail/forward',
      payload: {
        ...formValues,
        receiver:checkedList,
        id: this.state.editRecord.id,

      },
      callback() {
        message.success('转发通知成功');
        that.setState({
          forwardModal: false,
        });
        const {
          webMail: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSearch({
      is_read: '0',
      page: 1,
      per_page: 30,
    });
  };

  handleEdit = () => {
    const formValues = this.EditForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: `webMail/edit`,
      payload: {
        ...formValues,
        id: this.state.editRecord.id,
      },
      callback() {
        message.success('修改员工成功');
        that.setState({
          editModal: false,
        });
        const {
          webMail: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleDelete = id => {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: `webMail/remove`,
      payload: { id },
      callback: () => {
        message.success('删除通知成功');
        const {
          webMail: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  render() {
    const that = this;
    const {
      webMail: { data, loading, tableY, meta, searchParams, selectedRowKeys },
      global:{gridTableW}
    } = this.props;

    const defaultColumnProperties = {
      resizable: true,
    };
    const columns = [
      {
        name: '',
        width: 40,
        frozen:true,
        key: '_index2',
        formatter: (event) => {
          return <img style={{width:'24px'}} src={event.row.is_read===-1?mail:mailOpen} alt=""/>
        },
      },
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen:true,
        formatter: (event) => {
          const {
            webMail: { meta },
          } = this.props;
          return <p className={'index'}>{((meta.current_page - 1) * meta.per_page) + (event.value + 1)}</p>;
        },
      },
      {
        name: '时间',
        width: 160,
        key: 'created_at',
        frozen:true,
      },
      {
        name: '发件人',
        width: 100,
        key: 'operator_name',
        frozen:true,
      },
      {
        name: '公告类型',
        width: 100,
        key: 'type',
      },
      {
        name: '标题',
        width: 150,
        key: 'title',
      },
      {
        name: '内容',
        width: 200,
        key: 'content',
        formatter: (event) =>{
          let  regex = /(<([^>]+)>)/ig;
          return <p title={event.value.replace(regex, "")}>{event.value.replace(regex, "")}</p>
        }
      },
      {
        name: '附件',
        width: 330,
        key: 'attachments',
        formatter: (event) =>{
          if(event.value.length>0){
            return <p title={event.value[0].name}><img src={getFileType(event.value[0].name)} style={{marginRight:"5px",width:"20px",height:"20px"}} alt=""/>
            {event.value[0].name} 等{event.value.length}个附件</p>
          }else {
            return ''
          }
        }
      },
      {
        name: '操作',
        width: 200,
        key: 'right',
        classname:'operate',
        formatter: (event) => <Fragment>
                <Button
                  type="primary"
                  size="small"
                  icon="eye"
                  onClick={(e) => {

                    this.setState({
                      editRecord: event.row,
                      editModal: true,
                    });
                    if(event.row.is_read===-1){
                      const { dispatch } = this.props;
                      dispatch({
                        type: `webMail/read`,
                        payload: { id:event.row.id },
                        callback: () => {
                          const {
                            webMail: { searchParams },
                          } = that.props;
                          that.handleSearch(searchParams);
                        },
                      });
                    }

                  }
                  }
                >详情
                </Button>
                <Button
                  type="primary"
                  className='btn-green'
                  size="small"
                  icon="arrow-right"
                  onClick={(e) => {

                      this.setState({
                        editRecord:event.row,
                        forwardModal:true
                      })

                  }
                  }
                >转发
                </Button>
        </Fragment>,
      },
    ].map(c => ({  ...defaultColumnProperties,...c }));

    let totalWidth = 0;
    for (let i = 0; i < columns.length; i++) {
      totalWidth += columns[i].width;
    }
    if(totalWidth<gridTableW){
      columns[columns.length-3].width=columns[columns.length-3].width+gridTableW-totalWidth
    }

    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>通知公告</span>
      </div>
      <div className="table-page">
        <div className="table-condition">{this.renderSimpleForm()}</div>
        <div className={'table-data-content'}>
          <ReactDataGrid
            columns={columns}
            rowGetter={i => {
              return { ...data[i], _index: i };
            }}
            rowsCount={data.length}
            minHeight={tableY}
            rowSelection={{
              showCheckbox: false,
              enableShiftSelect: true,
              selectBy: {
                indexes: selectedRowKeys,
              },
            }}
            onRowClick={
              (row) => {
                this.props.dispatch({
                  type: 'webMail/changeSelectRow',
                  payload: [row],
                });
              }
            }

          />
          {
            loading&&<Loading />
          }
        </div>


      </div>
      <div className="table-pagination">
        <MyPagination searchCondition={{ ...searchParams }} meta={meta} handleSearch={this.handleSearch}/>
      </div>
      <Drawer
        title={`发布通知`}
        placement="right"
        keyboard={false}
        maskClosable={false}
        closable={false}
        onClose={() => {

          this.setState({
            addModal: false,
            editRecord: {},
          });
        }}
        width={900}
        visible={this.state.addModal}
      >
        <AddOrEditMeter
          handleSearch={this.handleSearch}
          onClose={() => {
            this.setState({
              addModal: false,
              editRecord: {},
            });
          }}
          onSave={this.handleAdd}
          wrappedComponentRef={(inst) => this.AddForm = inst}
        />
      </Drawer>
      <Drawer
        title={this.state.editRecord.title}
        placement="right"
        onClose={() => {
          this.setState({
            editModal: false,
            editRecord: {},
          });
        }}
        width={900}
        destroyOnClose
        visible={this.state.editModal}
      >
        <MailDetail

          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.AddForm = inst}
        />
      </Drawer>
      <Modal
        title={<BuildModalTitle visible={this.state.forwardModal} modalClass="forwardModal"
                                title={`转发 "${this.state.editRecord.title}"`}/>}
        visible={this.state.forwardModal}
        centered
        onOk={this.handleForward}
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        width={700}
        destroyOnClose
        className="forwardModal"
        onCancel={() => {
          this.setState({ forwardModal: false,editRecord:{} });
        }}

      >
        <ForwardForm editRecord={this.state.editRecord}
        wrappedComponentRef={(inst) => this.ForwardForm = inst}/>

      </Modal>
    </div>;
  }
}

export default BasicList;
